<?php

class CreditController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
		$req = $this->getRequest();
		$rest = new Application_Model_Rest();
		$auth = new Application_Model_Auth();
		if(!$auth->isLoggedIn()){
			$rurl="/credit";
			$this->_redirect('/login?rurl='.$rurl);
		}
		if($req->isGet()){
			$res_info = $rest->getUser();
			$creditRoleList = $rest->getUserCreditRole(-1);
			$this->view->CreditRoleList = $creditRoleList;
			$this->view->res_info = $res_info;
		}
		if($req->isXMLHttpRequest()){
			$uid = $auth->getUserId();
			$roleid = $req->getPost('giftid');
			if(!empty($roleid)){
				$res = $rest->getUser();
				$totalCredit = $res->User->credit;
				$creditRole = $rest->getUserCreditRole($roleid);
				if(!empty($totalCredit)&&!empty($creditRole)){
					$giftCredit = $creditRole[0]->gift_credit;
					if($totalCredit<$giftCredit){
						echo json_encode(array('msg'=>'error'));
						exit;
					}
					// postUserCreditConsume
					$info=array(
						'giftid'=>$roleid,
						'gift_credit'=>$giftCredit,
						'gift'=>$creditRole[0]->gift,
						'gift_title'=>$creditRole[0]->gift_title,
						'gift_limit'=>$creditRole[0]->gift_limit,
						'gift_starttime'=>$creditRole[0]->gift_starttime,
						'gift_expired'=>$creditRole[0]->gift_expired
					);
					$res_post = $rest->postUserCreditConsume($info);
					if(empty($res_post)|| !array_key_exists('voucherid',$res_post)){
						echo json_encode(array('msg'=>'error'));
						exit;
					}
					echo json_encode(array('msg'=>'success','res'=>$res_post->credit));
					exit;
					
				}else{
					echo json_encode(array('msg'=>'error'));
					exit;
				}
				
			}
		}
    }


}

